<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>Layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <link rel="stylesheet" href="../lib/layui-v2.5.5/css/layui.css" media="all">
    <link rel="stylesheet" href="../css/pms/PmsCategory.css">
    <link rel="stylesheet" href="../js/lay-module/treetable-lay/treetable.css">

    <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
</head>
<body>

<!--<h2>三级分类管理</h2>-->
<div>
    <div>
        <div class="layui-btn-group">
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm delNum"><i
                    class="layui-icon">&#xe640;</i>批量删除
            </button>
        </div>

        <div class="layui-btn-group" id="group02">
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm refresh"><i class="layui-icon">&#xe666;</i>刷新
            </button>
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm open-all">全部展开</button>
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm close-all">全部关闭</button>
        </div>
    </div>

    <hr class="layui-bg-green">
    <table class="layui-table layui-form" id="tree-table" lay-size="sm"></table>

</div>

<div id="edit-node" class="x-body" style="display: none;">
    <form class="layui-form layui-form-pane" id="edit-form" action="">
        <div class="layui-form-item center hh">
            <label class="layui-form-label" for="CatId">分类ID</label>
            <div class="layui-input-block">
                <input type="number" id="CatId" name="catId" class="layui-input readonly" readonly="readonly">
            </div>
        </div>
        <div class="layui-form-item center">
            <label class="layui-form-label" for="Title">节点名字</label>
            <div class="layui-input-block">
                <input type="text" id="Title" name="title" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item center">
            <label class="layui-form-label" for="ParentCid">父节点ID</label>
            <div class="layui-input-block">
                <input type="number" id="ParentCid" name="parentCid" class="layui-input readonly" readonly="readonly">
            </div>
        </div>
        <div class="layui-form-item center">
            <label class="layui-form-label" for="CatLevel">层级</label>
            <div class="layui-input-block">
                <input type="number" id="CatLevel" name="catLevel" class="layui-input readonly" readonly="readonly">
            </div>
        </div>
        <div class="layui-form-item center">
            <label class="layui-form-label" for="ShowStatus">是否显示</label>
            <div class="layui-input-block">
                <input type="number" id="ShowStatus" name="showStatus" class="layui-input readonly" readonly="readonly">
            </div>
        </div>
        <div class="layui-form-item center">
            <label class="layui-form-label" for="Sort">排序</label>
            <div class="layui-input-block">
                <input type="number" id="Sort" name="sort" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item center">
            <label class="layui-form-label" for="Icon">图标地址</label>
            <div class="layui-input-block">
                <input type="text" id="Icon" name="icon" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item center">
            <label class="layui-form-label" for="ProductUnit">计量单位</label>
            <div class="layui-input-block">
                <input type="text" id="ProductUnit" name="productUnit" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item center">
            <label class="layui-form-label" for="ProductCount">商品数量</label>
            <div class="layui-input-block">
                <input type="number" id="ProductCount" name="productCount" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="editnode" style="margin-left: 150px">确定修改</button>
            </div>
        </div>
    </form>
</div>

<div id="add-node" class="x-body" style="display: none;">
    <form class="layui-form" id="add-form" action="">
        <input type="text" id="NodeID" name="id" style="display:none;" class="layui-input">
        <div class="layui-form-item center">
            <label class="layui-form-label" style="width: 100px">节点名字</label>
            <div class="layui-input-block">
                <input type="text" id="inputId" name="title" style="width: 240px" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn layui-btn-primary" onclick="btn1()" style="margin-left: 120px">取消</button>
                <button class="layui-btn" lay-submit lay-filter="addnode">确定</button>
            </div>
        </div>
    </form>
</div>


<script src="../lib/jquery-3.4.1/jquery-3.4.1.min.js"></script>
<script src="../lib/layui-v2.5.5/layui.js"></script>


<!-- 注意：如果你直接复制所有代码到本地，上述js路径需要改成你本地的 -->

<script type="text/javascript">
    layui.config({
        base: '../js/lay-module/treetable-lay/js/',
    })
    layui.use(['treeTable', 'layer', 'code', 'form'], function () {
        var o = layui.$,
            form = layui.form,
            layer = layui.layer,
            treeTable = layui.treeTable;
        // 直接下载后url: './data/table-tree.json',这个配置可能看不到数据，改为data:[],获取自己的实际链接返回json数组

        $.ajax({
            type: 'post',
            url: '/product/pmscategory/getLastList',
            dataType: 'json',
            success: function (lastList) {
                //将取出的key改为与layui tree匹配的key，name改为title,catId改为id
                let last01 = changeTreeDate(lastList, 'title', 'name');
                let last02 = changeTreeDate(last01, 'id', 'catId');
                var lastid = last02 ? last02.data : null;

                function getData() {
                    var dataAll = [];
                    $.ajax({
                        type: 'post',
                        url: '/product/pmscategory/getTree',
                        dataType: 'json',
                        async: false,       //将请求设置为同步，成功获得数据后方法才返回dataAll
                        success: function (res) {
                            //console.log(res);
                            let data01 = changeTreeDate(res, 'title', 'name');
                            let data02 = changeTreeDate(data01, 'id', 'catId');
                            let data03 = changeTreeDate(data02, 'pid', 'parentCid');
                            //redertable(data03);
                            // console.log(data03.data);
                            dataAll = data03.data;
                            //console.log(dataAll);
                        }
                    });
                    //console.log(dataAll);
                    return dataAll;
                }

                // 渲染表格
                var redertable = function () {
                    var re = treeTable.render({
                        elem: '#tree-table',
                        height: 'full-160',
                        icon_key: 'title',// 必须
                        treeColIndex: 1,	//树形图标显示在第几列
                        //id: treeTable,       //用以刷新树表
                        //treeSpid: '1',		//最上级的父级id
                        treeIdName: 'id',	//id字段的名称
                        treePidName: 'pid',	//父级节点字段
                        //openName:'name',  //自定义默认展开的字段名
                        treeDefaultClose: false,	//是否默认折叠
                        treeLinkage: false,		//父级展开时是否自动展开所有子级
                        // toolbar: '#toolbarDemo',
                        data: getData(),
                        is_checkbox: true,
                        checkChild: false, //选中父级时 是否选选择所有子级
                        checked: {
                            key: 'id',
                            //data: [0, 1, 4, 10, 11, 5, 2, 6, 7, 3, 8, 9],
                        },
                        end: function (e) {
                            form.render();
                        },
                        cols: [

                            {
                                key: 'title',
                                title: '名称',
                                template: function (item) {
                                    if (item.showStatus == 1) {
                                        return '<span style="color:black;">' + item.title + '</span>';
                                    } else if (item.showStatus == 0) {
                                        return '<span style="color:#aaa;">' + item.title + '</span>';
                                    }
                                }
                            },
                            {
                                key: 'id',
                                title: 'ID',
                                template: function (item) {
                                    if (item.showStatus == 1) {
                                        return '<span style="color:black;">' + item.id + '</span>';
                                    } else if (item.showStatus == 0) {
                                        return '<span style="color:#aaa;">' + item.id + '</span>';
                                    }
                                }
                            },
                            {
                                key: 'pid',
                                title: '父ID',
                                template: function (item) {
                                    if (item.showStatus == 1) {
                                        return '<span style="color:black;">' + item.pid + '</span>';
                                    } else if (item.showStatus == 0) {
                                        return '<span style="color:#aaa;">' + item.pid + '</span>';
                                    }
                                }
                            },
                            {
                                key: 'catLevel',
                                title: '层级',
                                template: function (item) {
                                    if (item.showStatus == 1) {
                                        return '<span style="color:black;">' + item.catLevel + '</span>';
                                    } else if (item.showStatus == 0) {
                                        return '<span style="color:#aaa;">' + item.catLevel + '</span>';
                                    }
                                }
                            },
                            {
                                key: 'sort',
                                title: '排序',
                                template: function (item) {
                                    if (item.showStatus == 1) {
                                        return '<span style="color:black;">' + item.sort + '</span>';
                                    } else if (item.showStatus == 0) {
                                        return '<span style="color:#aaa;">' + item.sort + '</span>';
                                    }
                                }
                            },
                            {
                                key: 'icon',
                                title: '图标',
                                template: function (item) {
                                    if (item.showStatus == 1) {
                                        return '<span style="color:black;">' + item.icon + '</span>';
                                    } else if (item.showStatus == 0) {
                                        return '<span style="color:#aaa;">' + item.icon + '</span>';
                                    }
                                }
                            },
                            {
                                key: 'productUnit',
                                title: '计量单位',
                                template: function (item) {
                                    if (item.showStatus == 1) {
                                        return '<span style="color:black;">' + item.productUnit + '</span>';
                                    } else if (item.showStatus == 0) {
                                        return '<span style="color:#aaa;">' + item.productUnit + '</span>';
                                    }
                                }
                            },
                            {
                                key: 'productCount',
                                title: '产品数量',
                                template: function (item) {
                                    if (item.showStatus == 1) {
                                        return '<span style="color:black;">' + item.productCount + '</span>';
                                    } else if (item.showStatus == 0) {
                                        return '<span style="color:#aaa;">' + item.productCount + '</span>';
                                    }
                                }
                            },
                            {
                                key: 'showStatus',
                                title: '是否展示',
                                align: 'center',
                                template: function (item) {
                                    //checked默认选中
                                    if (item.showStatus == 1) {
                                        return '<input type="checkbox" name="close" lay-skin="switch" lay-text="ON|OFF" checked>';
                                    } else if (item.showStatus == 0) {
                                        return '<input type="checkbox" name="open" lay-skin="switch" lay-text="ON|OFF">';
                                    }
                                }
                            },

                            {
                                title: '操作',
                                align: 'center',

                                template: function (item) {
                                    if (item.catLevel == 1) {


                                        return '  <div class="layui-btn-group">\n' +
                                            '        <button type="button" class="layui-btn layui-btn-xs layui-btn-normal" lay-filter="add">增加</button>\n' +
                                            '        <button type="button" class="layui-btn layui-btn-xs layui-btn-normal" lay-filter="update">编辑</button>\n' +
                                            '        <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" lay-filter="del">删除</button>\n' +
                                            '    </div>';
                                    } else if (item.catLevel == 2) {

                                        return '  <div class="layui-btn-group">\n' +
                                            '        <button type="button" class="layui-btn layui-btn-xs layui-btn-normal" lay-filter="add">增加</button>\n' +
                                            '        <button type="button" class="layui-btn layui-btn-xs layui-btn-normal" lay-filter="update">编辑</button>\n' +
                                            '        <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" lay-filter="del">删除</button>\n' +
                                            '    </div>';
                                    } else if (item.catLevel == 3) {
                                        return '  <div class="layui-btn-group">\n' +
                                            '        <button type="button" class="layui-btn layui-btn-xs layui-btn-normal" lay-filter="add">增加</button>\n' +
                                            '        <button type="button" class="layui-btn layui-btn-xs layui-btn-normal" lay-filter="update">编辑</button>\n' +
                                            '        <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" lay-filter="del">删除</button>\n' +
                                            '    </div>';
                                        //return '<button class="layui-btn-disabled">添加</button> <button>编辑</button> <button>删除</button>';
                                    }
                                }

                            }

                        ]
                    });


                    // 监听增加自定义
                    treeTable.on('tree(add)', function (data) {
                        var i = data.item;
                        if (i.catLevel == 3) {
                            layer.msg('当前层级菜单不支持增加功能', {icon: 2})
                        } else {
                            //layer.msg(JSON.stringify(data.item));
                            $("#NodeID").val(i.id);
                            index0pen = layer.open({
                                type: 1,
                                title: "新增",
                                area: ['500px', '200px'],
                                content: $("#add-node"),
                            });

                            form.on('submit(addnode)', function (data) {

                                var nodeData = data.field;
                                var catId = lastid[0].id + 1;
                                var name = nodeData.title;
                                var parentCid = i.id;
                                var catLevel = i.catLevel + 1;
                                var kk = {
                                    "catId": catId,
                                    "name": name,
                                    "parentCid": parentCid,
                                    "catLevel": catLevel,
                                    "showStatus": 1,
                                    "sort": 0,
                                    "productCount": 0
                                };
                                console.log(JSON.stringify(catId));
                                console.log(JSON.stringify(parentCid));
                                console.log(JSON.stringify(catLevel));
                                var str02 = JSON.stringify(kk);
                                console.log(str02);

                                if (document.getElementById("inputId").value == "") {
                                    layer.msg('请输入菜单名称', {icon: 0});
                                    return false;

                                } else {
                                    $.ajax({
                                        url: '/product/pmscategory/save',
                                        type: 'post',
                                        dataType: 'json',
                                        contentType: 'application/json;charset=utf-8',
                                        data: str02,
                                        success: function (r) {
                                            redertable();
                                            layer.close(index0pen);
                                            layer.msg('保存成功', {icon: 6});
                                        },
                                        error: function (s) {
                                            layer.msg('保存出错了');
                                        }
                                    });

                                }

                            });
                            document.getElementById("inputId").value = "";

                        }

                    })
                    // 监听修改自定义
                    treeTable.on('tree(update)', function (data) {
                        var i = data.item;
                        $("#CatId").val(i.id);
                        $("#Title").val(i.title);
                        $("#ParentCid").val(i.pid);
                        $("#CatLevel").val(i.catLevel);
                        $("#ShowStatus").val(i.showStatus);
                        $("#Sort").val(i.sort);
                        $("#Icon").val(i.icon);
                        $("#ProductUnit").val(i.productUnit);
                        $("#ProductCount").val(i.productCount);

                        index0pen = layer.open({
                            type: 1,
                            title: "编辑详情",
                            content: $("#edit-node"),
                            area: ['450px', '600px'],//弹出框大小
                        });

                        form.on('submit(editnode)', function (data) {
                            //alert(JSON.stringify(data.data));
                            var nodeData = data.field;
                            let str01 = changeTreeDate(nodeData, 'name', 'title');
                            let str02 = changeTreeDate(str01, 'catId', 'id');
                            let str03 = changeTreeDate(str02, 'parentCid', 'pid');
                            //console.log(JSON.stringify(str03));
                            $.ajax({
                                url: '/product/pmscategory/update',
                                type: 'post',
                                dataType: 'json',
                                contentType: 'application/json;charset=utf-8',
                                data: JSON.stringify(str03),
                                success: function (r) {
                                    if (r["code"] == 500) { //修改失败
                                        layer.msg(r["msg"], {icon: 5});
                                    } else {  //修改成功
                                        redertable();
                                        layer.close(index0pen);
                                        layer.msg(r["msg"], {icon: 6});
                                    }
                                },
                                error: function (s) {
                                    layer.msg('修改出错了');
                                }
                            });
                            return false;
                        });


                    })
                    //监听删除自定义
                    treeTable.on('tree(del)', function (data) {
                        var i = data.item;
                        if (i.catLevel == 1) {
                            layer.msg('该菜单下有子菜单，不可删除', {icon: 2})
                        } else {
                            layer.confirm('此操作不可逆，您确定要删除吗？', {
                                btn: ['确定', '取消'] //按钮
                            }, function () {
                                $.ajax({
                                    url: '/product/pmscategory/delete',
                                    type: 'post',
                                    dataType: 'json',
                                    data: {
                                        id: i.id
                                    },
                                    success: function (r) {
                                        redertable();
                                        layer.msg('数据删除成功', {icon: 6});
                                    },
                                    error: function (s) {
                                        layer.msg('删除出错了', {icon: 5});
                                    }
                                });
                            })

                        }

                    })


                    //批量删除
                    o('.delNum').click(function () {
                        //获取选中数量
                        var selectCount = treeTable.checked(re).length;

                        if (selectCount == 0) {
                            layer.msg('请选中一行参数进行操作')
                        } else {

                            var isStr = "";
                            isStr = treeTable.checked(re).join(',');
                            console.log(isStr);

                            layer.confirm('当前选中参数' + treeTable.checked(re).join(',') + '此操作不可逆，您确定要删除吗？', {
                                btn: ['确定', '取消'] //按钮
                            }, function () {
                                $.ajax({
                                    url: '/product/pmscategory/deleteNum',
                                    type: 'post',
                                    dataType: 'json',
                                    data: {
                                        isStr: isStr
                                    },
                                    success: function (r) {
                                        redertable();
                                        layer.msg('删除成功', {icon: 6});

                                    },
                                    error: function (s) {
                                        redertable();
                                        layer.msg('删除出错了', {icon: 5});
                                    }
                                });
                            })

                        }

                    })


                    // 刷新重载树表（一般在异步处理数据后刷新显示）
                    o('.refresh').click(function () {
                        redertable();

                    })


                    // 全部展开
                    o('.open-all').click(function () {
                        treeTable.openAll(re);
                    })
                    // 全部关闭
                    o('.close-all').click(function () {
                        treeTable.closeAll(re);
                    })


                    o('.layui-select-title').click(function () {
                        o(this).parent().hasClass('layui-form-selected') ? o(this).next().hide() : o(this).next().show(), o(this).parent().toggleClass('layui-form-selected');
                    })
                    o(document).on("click", function (i) {
                        !o(i.target).parent().hasClass('layui-select-title') && !o(i.target).parents('table').length && !(!o(i.target).parents('table').length && o(i.target).hasClass('layui-icon')) && o(".layui-form-select").removeClass("layui-form-selected").find('.layui-anim').hide();
                    })
                }
                redertable();

            }
        });


    })


    function changeTreeDate(zf_jsonObj, newKey, oldKey) {
        let str = JSON.stringify(zf_jsonObj);
        let reg = new RegExp(oldKey, 'g');
        let newStr = str.replace(reg, newKey);
        return JSON.parse(newStr);
    }

</script>
</body>